<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<div class="card">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
            <h4 class="mb-0">
                <c:choose>
                    <c:when test="${mode eq 'sequential'}">顺序练习</c:when>
                    <c:when test="${mode eq 'random'}">随机练习</c:when>
                    <c:when test="${mode eq 'category'}">专项练习</c:when>
                    <c:when test="${mode eq 'wrong_question'}">错题练习</c:when>
                </c:choose>
            </h4>
            <div class="progress" style="width: 200px;">
                <div class="progress-bar" role="progressbar" style="width: 0%">0/0</div>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div id="questionContainer">
            <div class="text-center">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p>正在加载题目...</p>
            </div>
        </div>
        <div class="mt-3">
            <button class="btn btn-primary" id="submitBtn" style="display: none;">提交答案</button>
            <button class="btn btn-secondary ms-2" id="nextBtn" style="display: none;">下一题</button>
        </div>
    </div>
</div>

<!-- 答题结果统计模态框 -->
<div class="modal fade" id="summaryModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">练习完成</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- 内容将由JavaScript动态生成 -->
            </div>
            <div class="modal-footer">
                <a href="${pageContext.request.contextPath}/question/list" class="btn btn-secondary">返回列表</a>
                <button type="button" class="btn btn-primary" onclick="restartTraining()">重新练习</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    let questions = [];
    let currentIndex = 0;
    let answers = [];
    let summaryModal = new bootstrap.Modal(document.getElementById('summaryModal'));

    // 加载题目数据
    function loadQuestions() {
        // 先检查登录状态
        $.ajax({
            url: '${pageContext.request.contextPath}/user/api/check-login',
            type: 'GET',
            success: function(response) {
                if (response.code === 200) {
                    // 已登录，加载题目
                    loadQuestionData();
                } else {
                    // 未登录，保存当前URL并跳转到登录页
                    window.location.href = '${pageContext.request.contextPath}/user/login?redirect=' + 
                        encodeURIComponent(window.location.pathname + window.location.search);
                }
            }
        });
    }

    // 实际加载题目的函数
    function loadQuestionData() {
        $.ajax({
            url: '${pageContext.request.contextPath}/question/api/training/${mode}',
            type: 'GET',
            data: {
                categoryId: '${param.categoryId}'
            },
            success: function(response) {
                if (response.code === 200) {
                    questions = response.data;
                    answers = new Array(questions.length);
                    showQuestion(0);
                    $('#submitBtn').show();
                } else {
                    $('#questionContainer').html(`
                        <div class="alert alert-warning">
                            ${response.message}
                            <br>
                            <a href="${pageContext.request.contextPath}/" class="btn btn-primary mt-3">返回首页</a>
                        </div>
                    `);
                }
            },
            error: function(xhr) {
                if (xhr.status === 401) {
                    window.location.href = '${pageContext.request.contextPath}/user/login';
                } else {
                    $('#questionContainer').html(`
                        <div class="alert alert-danger">
                            加载题目失败，请稍后重试
                            <br>
                            <a href="${pageContext.request.contextPath}/" class="btn btn-primary mt-3">返回首页</a>
                        </div>
                    `);
                }
            }
        });
    }

    function showQuestion(index) {
        let question = questions[index];
        let html = `
            <h5 class="mb-3">${index + 1}. \${question.title}</h5>
            <div class="mb-4">
                <div class="d-flex justify-content-between">
                    <span class="badge bg-primary">\${question.categoryName}</span>
                    <span class="badge \${question.difficulty == 1 ? 'bg-success' : question.difficulty == 2 ? 'bg-warning' : 'bg-danger'}">
                        \${question.difficulty == 1 ? '简单' : question.difficulty == 2 ? '中等' : '困难'}
                    </span>
                </div>
            </div>
            <div class="mb-4">
                <p class="card-text">\${question.content}</p>
            </div>
            <div class="question-options">`;
        
        // 根据题目类型使用不同的input类型
        let inputType = question.isMultiple ? 'checkbox' : 'radio';
        
        ['A', 'B', 'C', 'D'].forEach(option => {
            html += `
                <div class="form-check mb-2">
                    <input class="form-check-input" type="\${inputType}" name="answer" value="\${option}" id="option\${option}">
                    <label class="form-check-label" for="option\${option}">
                        \${option}. \${question['option' + option]}
                    </label>
                </div>`;
        });
        
        html += `</div>`;
        if (question.isMultiple) {
            html += '<div class="text-muted mb-2">（多选题：请选择所有正确答案）</div>';
        }
        
        $('#questionContainer').html(html);
        updateProgress();
    }

    function updateProgress() {
        if (questions.length === 0) {
            $('.progress-bar').css('width', '0%').text('0/0');
            return;
        }
        let progress = ((currentIndex + 1) / questions.length * 100).toFixed(0);
        $('.progress-bar')
            .css('width', progress + '%')
            .text(`${currentIndex + 1}/${questions.length}`);
    }

    $('#submitBtn').click(function() {
        let question = questions[currentIndex];
        let userAnswer;
        if (question.isMultiple) {
            userAnswer = $('input[name="answer"]:checked').map(function() {
                return $(this).val();
            }).get().sort().join(',');
            if (!userAnswer) {
                alert('请至少选择一个答案');
                return;
            }
        } else {
            userAnswer = $('input[name="answer"]:checked').val();
            if (!userAnswer) {
                alert('请选择一个答案');
                return;
            }
        }

        $.ajax({
            url: '${pageContext.request.contextPath}/question/api/submit',
            type: 'POST',
            data: {
                questionId: question.id,
                answer: userAnswer,
                isMultiple: question.isMultiple
            },
            success: function(response) {
                if (response.code === 200) {
                    answers[currentIndex] = {
                        answer: userAnswer,
                        correct: response.data.correct,
                        correctAnswer: response.data.correctAnswer
                    };
                    showResult(response.data.correct);
                }
            }
        });
    });

    function showResult(isCorrect) {
        // 禁用选项和提交按钮
        $('input[name="answer"]').prop('disabled', true);
        $('#submitBtn').hide();
        $('#nextBtn').show();

        // 显示正确答案
        $('input[name="answer"]').each(function() {
            let $parent = $(this).closest('.form-check');
            let question = questions[currentIndex];
            let currentOption = $(this).val();
            
            // 判断当前选项是否是正确答案
            let isCorrectOption = question.isMultiple ? 
                question.correctAnswers.includes(currentOption) :
                question.answer === currentOption;
                
            // 如果是正确答案，显示绿色
            if (isCorrectOption) {
                $parent.addClass('correct-answer');
            }
            
            // 如果当前选项被选中且不是正确答案，显示红色
            if ($(this).prop('checked') && !isCorrectOption) {
                $parent.addClass('wrong-answer');
            }
        });
    }

    $('#nextBtn').click(function() {
        currentIndex++;
        if (currentIndex < questions.length) {
            showQuestion(currentIndex);
            $('#submitBtn').show();
            $('#nextBtn').hide();
        } else {
            showSummary();
        }
    });

    function showSummary() {
        // 计算正确数量和正确率
        let correctCount = 0;
        let totalAnswered = 0;
        
        for (let i = 0; i < questions.length; i++) {
            if (answers[i] && answers[i].correct !== undefined) {
                totalAnswered++;
                if (answers[i].correct) {
                    correctCount++;
                }
            }
        }
        
        let accuracy = totalAnswered > 0 ? (correctCount / totalAnswered * 100).toFixed(1) : 0;
        
        // 构建统计信息HTML
        let html = '<div class="row text-center">';
        html += '<div class="col-4">';
        html += '<h5>总题数</h5>';
        html += '<p class="h3 mb-0">' + questions.length + '</p>';
        html += '</div>';
        html += '<div class="col-4">';
        html += '<h5>正确数</h5>';
        html += '<p class="h3 mb-0">' + correctCount + '</p>';
        html += '</div>';
        html += '<div class="col-4">';
        html += '<h5>正确率</h5>';
        html += '<p class="h3 mb-0">' + accuracy + '%</p>';
        html += '</div>';
        html += '</div>';
        html += '<hr>';
        html += '<div class="mt-3">';
        html += '<h5>答题详情：</h5>';
        html += '<div class="list-group">';
        
        // 添加每道题的答题情况
        for (let i = 0; i < questions.length; i++) {
            let answer = answers[i];
            if (answer && answer.correct !== undefined) {
                html += '<div class="list-group-item">';
                html += '<div class="d-flex w-100 justify-content-between">';
                html += '<h6 class="mb-1">第' + (i + 1) + '题：' + questions[i].title + '</h6>';
                html += '<span class="badge ' + (answer.correct ? 'bg-success' : 'bg-danger') + '">';
                html += answer.correct ? '正确' : '错误';
                html += '</span>';
                html += '</div>';
                html += '<p class="mb-1">你的答案：' + answer.answer + '</p>';
                if (!answer.correct) {
                    html += '<small class="text-muted">正确答案：' + answer.correctAnswer + '</small>';
                }
                html += '</div>';
            }
        }
        
        html += '</div></div>';
        
        $('.modal-body').html(html);
        summaryModal.show();
    }

    function restartTraining() {
        // 重置状态
        currentIndex = 0;
        answers = [];
        // 重新加载题目
        loadQuestions();
        // 关闭模态框
        summaryModal.hide();
    }

    // 绑定重新练习按钮的点击事件
    $('#summaryModal button[onclick="restartTraining()"]').click(function(e) {
        e.preventDefault();
        restartTraining();
    });

    // 初始化
    loadQuestions();
});
</script>

<style>
.correct-answer {
    background-color: rgba(40, 167, 69, 0.1);
    border-color: #28a745;
}
.wrong-answer {
    background-color: rgba(220, 53, 69, 0.1);
    border-color: #dc3545;
}
.question-options .form-check {
    padding: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    margin-bottom: 0.5rem;
}
</style>
